package com.twu.biblioteca.auth;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Authenticator {

    private Map<String, User> usernameToUsers = new HashMap<String, User>();
    private boolean isLoggedIn = false;
    private User loggedInUser = null;

    public Authenticator() {
    }

    public Authenticator(List<User> users) {
        for (User user: users) {
            usernameToUsers.put(user.getUsername(), user);
        }
    }

    public boolean login(String username, String password) {
        if (usernameToUsers.get(username) == null) return false;

        isLoggedIn = usernameToUsers.get(username).checkPassword(password);
        if (isLoggedIn) {
            loggedInUser = usernameToUsers.get(username);
        }
        return isLoggedIn;
    }

    public boolean isLoggedIn() {
        return isLoggedIn;
    }

    public void logout() {
        isLoggedIn = false;
        loggedInUser = null;
    }

    public User getLoggedInUser() {
        return loggedInUser;
    }

}
